package A3GCConcreteTestCase;

import java.util.concurrent.ConcurrentLinkedQueue;

import A3JGroups.A3JGMessage;
import A3JGroupsGC.GCFollowerRole;

public class ConcreteFollower extends GCFollowerRole 
{
	ConcurrentLinkedQueue<A3JGMessage> myProcessQueue;
	
	public static boolean locations_operational_flag = false;
	
	public ConcreteFollower(int resourceCost, String groupName) 
	{
		super(resourceCost, groupName);
		
		myProcessQueue = new ConcurrentLinkedQueue<A3JGMessage>();
	}

	@Override
	public void run() 
	{
		while ( this.active )
		{
			// check for work to do
			if ( !(myProcessQueue.isEmpty()) )
			{
				A3JGMessage mex = myProcessQueue.poll();
				try
				{	
					String splits[];
					splits = mex.getContent().toString().split("#");
					if ( splits.length < 5 && locations_operational_flag )
					{
						System.out.println(this.getNode().getID() + "," + getChan().getAddress().toString() + " invalid message??????");
					}
					else
					{
						String groupname, num;
						//String addr;
						groupname = splits[0];
						num       = splits[1];
						//addr      = splits[2];
									
						int processtime = Integer.parseInt( num );
						
						if ( processtime <= 0 )
							processtime = 1;
						
						System.out.println(this.getNode().getID() + "," + getChan().getAddress().toString() + " processing (also known as sleeping "+ processtime + "). came for group " + groupname + ".");
						
						// let's "process"
						try 
						{
							Thread.sleep(processtime * 1000 );
						} 
						catch (InterruptedException e) 
						{
							e.printStackTrace();
						}
						
						A3JGMessage msg = new A3JGMessage();
						//msg.setContent(Integer.toString(processtime) + "#" + addr );
						msg.setContent( mex.getContent().toString() );
						msg.setType(true);
						System.out.println(this.getNode().getID() + "," + getChan().getAddress().toString() + " is sending a message to supervisor with <" + msg.getContent().toString() + ">");
						sendMessageToSupervisor( msg );
					}
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}
			else
			{
				try 
				{
					Thread.sleep(500); // go to sleep for a bit.
				} 
				catch (InterruptedException e) 
				{
					e.printStackTrace();
				} 
			}
		}
	}

	@Override
	public void messageFromSupervisor(A3JGMessage msg) 
	{
		System.out.println("Concrete Follower[" + this.getNode().getID() + "," + getChan().getAddress().toString() + "] got a message <" + msg.getContent().toString() + "> addr is <" + getChan().getAddress().toString() + ">" );
		myProcessQueue.add(msg);
	}

}
